package oocl.com.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import oocl.com.dao.UserDao;
import oocl.com.pojo.User;
import oocl.com.util.DBUtil;

public class UserDaoImpl implements UserDao {

	@Override
	public int addUser(User c) {
		String sql = "insert into newUserTable(uname, sal, birth, sex) values (?,?,?,?)";
		
		PreparedStatement pst =null;
		Connection con = null;
		int m = 0; 
		
		try {
			con = DBUtil.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, c.getUname());
			pst.setDouble(2, c.getSal());
			pst.setDate(3, new java.sql.Date(c.getBirth().getTime()));
			pst.setInt(4, c.getSex());
			pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(con, pst, null);
		}
		
		return m;
	}

	@Override
	public List<User> getAllUser() {
		List<User> list = new ArrayList<User>();
		String sql = "select * from newUserTable";
		PreparedStatement pst = null;
		ResultSet rs = null;
		Connection con = DBUtil.createConnection();
		
		try {
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			
			while(rs.next()){
				User c = new User();
				c.setUname(rs.getString("uname"));
				c.setSal(rs.getDouble("sal"));
				c.setBirth(new Date(rs.getDate("birth").getTime()));
				c.setSex(rs.getInt("sex"));
				
				list.add(c);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(con, pst, rs);
		}
		return list;
	}
	
	public static void main(String[] args) {
		UserDaoImpl impl = new UserDaoImpl();
		User c = new User("jordan", 11.2, new Date(), 1);
		impl.addUser(c);
	}
}
